package com.caoxw.Android.CityBus;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView.OnEditorActionListener;

public class DownLoadDataFileActivity extends Activity implements Runnable {
	private ListView m_objDataList = null;
	private DownDataAdapt m_adapter = null;
	private Handler hander = null;
	private ProgressDialog m_dlgPro = null;
	private Button m_btnDownLoad = null;
	private Button m_btnCancel = null;
	private ArrayList<CityDataItem> m_DataItem = null;
	private EditText m_objCitySearch = null ;
	private Thread m_mainThread  = null ;
	private	String	m_strSearchCity = null;
	private final  int MSG_FLAG_PROCESS =  3;
	private final  int MSG_FLAG_ERROR =  11;
	private final  int MSG_FLAG_DOWN_START = 4;
	private final  int MSG_FLAG_DOWNLIST_START = 2;
	private final  int MSG_FALG_DOWNLIST_FINISHED_ALL = 5;
	private final  int MSG_FALG_DOWNLIST_FINISHED_ITEM = 6;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.downloaddata);
		m_btnDownLoad = (Button) this.findViewById(R.id.btnDownload);
		m_btnCancel = (Button) this.findViewById(R.id.btnCnncel);
		m_objDataList = (ListView) this.findViewById(R.id.datalist);
		
		
		m_objCitySearch = (EditText) this.findViewById(R.id.editCitySearch);
		
		m_objCitySearch.setOnEditorActionListener(new OnEditorActionListener(){

			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				// TODO Auto-generated method stub
				m_strSearchCity = v.getText().toString();
				System.out.println("Thred Status:");
				System.out.println(m_mainThread.getState());
				if(null == m_mainThread || Thread.State.TERMINATED == m_mainThread.getState() || Thread.State.NEW == m_mainThread.getState()){
					m_mainThread = new Thread(DownLoadDataFileActivity.this);
					m_mainThread.start();
				}
				return false;
			}
			
		});
		

		m_adapter = new DownDataAdapt(this);

		m_btnCancel.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}

		});
		m_btnDownLoad.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Thread(){
					public void run(){
						StartDownLoad();
						
					}
					
				}.start();
				m_btnDownLoad.setEnabled(false);
			}

		});

		// m_objDataList.setItemsCanFocus(false);
		m_objDataList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		m_objDataList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				m_adapter.switchSelected(arg2);
				m_objDataList.requestFocusFromTouch();
				//m_objDataList.setSelection(arg2);
			}

		});
		hander = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
					m_objDataList.setAdapter(m_adapter);
					m_dlgPro.dismiss();
					break;
				case 10:
					Toast.makeText(DownLoadDataFileActivity.this, "网络出错，无法从服务器获取数据！请检查你的网络是否可用和软件是否是最新版本？", Toast.LENGTH_SHORT).show();
					m_dlgPro.dismiss();
					break;
				case 1:
					m_objDataList.requestFocus();
					m_dlgPro.setMessage("正在处理数据...");
					m_dlgPro.show();
					break;
				case MSG_FLAG_DOWN_START:
					System.out.println("MSG_FLAG_DOWN_START");
					
					m_objDataList.requestFocusFromTouch();
					m_objDataList.setSelection(msg.arg1);
					m_adapter.setProgress(msg.arg1, 0);
					m_adapter.setOtherInfo(msg.arg1,"大小:"	
							+ String.valueOf(m_DataItem.get(msg.arg1).Size / 1024) + "k 0%\n版本:"
							+ m_DataItem.get(msg.arg1).UpdateTime);
					break;
				case MSG_FLAG_DOWNLIST_START:
					m_objDataList.requestFocus();
					m_dlgPro.setMessage("正在下载列表数据...");
					m_dlgPro.show();
					break;
				case MSG_FLAG_PROCESS:
					m_adapter.setProgress(msg.arg1, msg.arg2);
					m_adapter.setOtherInfo(msg.arg1,"大小:"	
							+ String.valueOf(m_DataItem.get(msg.arg1).Size / 1024) + "k  " + String.valueOf(msg.arg2) + "%\n更新:"
							+ m_DataItem.get(msg.arg1).UpdateTime);
					break;
				case MSG_FLAG_ERROR:
					m_adapter.setOtherInfo(msg.arg1,(String)msg.obj);
					break;
				case MSG_FALG_DOWNLIST_FINISHED_ALL:
					m_btnDownLoad.setEnabled(true);
					Toast.makeText(DownLoadDataFileActivity.this, "所有下载己经完成！", Toast.LENGTH_SHORT).show();
					break;
				case MSG_FALG_DOWNLIST_FINISHED_ITEM:
					m_adapter.setSelected(msg.arg1, false);
					break;
					
					
		
					
			
				}
			}
		};

		m_btnCancel.requestFocus();
		m_dlgPro = new ProgressDialog(DownLoadDataFileActivity.this);
		m_dlgPro.setTitle("Waiting...");
		m_mainThread = new Thread(this);
		m_mainThread.start();

	}

	public void run() {
		// TODO Auto-generated method stub
		hander.sendEmptyMessage(MSG_FLAG_DOWNLIST_START);
		m_adapter.clear();
		HttpUtil up = new HttpUtil();
		m_DataItem = up.getDataList(m_strSearchCity);
		if(up.isError){
			hander.sendEmptyMessage(10);
			return;
		}

		String[] arrItems = new String[m_DataItem.size()];
		hander.sendEmptyMessage(1);
		m_adapter.clear();
		for (int i = 0; i < m_DataItem.size(); i++) {
			m_adapter.addItem(m_DataItem.get(i).Name, "大小:"
					+ String.valueOf(m_DataItem.get(i).Size / 1024) + "k\n更新:"
					+ m_DataItem.get(i).UpdateTime, false, 0);
		}
		hander.sendEmptyMessage(0);

		// m_objDataList.setAdapter(m_adapter);
		// m_adapter.notifyDataSetChanged();

	}

	public boolean DownDataFile(int position,String FilePath, String SavePath) {
		try {
			URL myURL = new URL(FilePath);
			URLConnection conn = myURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();

			int fileSize = conn.getContentLength();// 根据响应获取文件大小
			if (fileSize <= 0){
				 sendMsg(MSG_FLAG_ERROR,position,0,"下载失败：\n无法获知文件大小");
				 return false;
			}
				//throw new RuntimeException("无法获知文件大小 "+ FilePath);
			if (is == null){
				sendMsg(MSG_FLAG_ERROR,position,0,"下载失败：\n本地无法写入");
				 return false;
				//throw new RuntimeException("stream is null");
			}

			FileOutputStream fos = getApplicationContext().openFileOutput(
					SavePath, getApplicationContext().MODE_WORLD_READABLE);
			byte buf[] = new byte[1024];
			int downLoadFileSize = 0;

			do {
				// 循环读取
				int numread = is.read(buf);
				if (numread == -1) {
					break;
				}
				fos.write(buf, 0, numread);
				downLoadFileSize += numread;
				sendMsg(MSG_FLAG_PROCESS,position,downLoadFileSize*100/fileSize,null);

			} while (true);
			fos.close();
			is.close();
			sendMsg(MSG_FALG_DOWNLIST_FINISHED_ITEM,position);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;

	}
	private void StartDownLoad(){
		int ErrorCount = 0;
		for(int i=0;i<m_adapter.getCount();i++){
			if(m_adapter.getSelected(i)){
				sendMsg(MSG_FLAG_DOWN_START,i);
				ErrorCount = 0;
				while(ErrorCount<3){
					if(DownDataFile(i,m_DataItem.get(i).FileName,String.valueOf(m_DataItem.get(i).Id) + ".cbus"))
						ErrorCount = 3;
					else
						ErrorCount++;
				}
				
			}
		}
		sendMsg(MSG_FALG_DOWNLIST_FINISHED_ALL);
		
	}
	private void sendMsg(int flag,int arg1) {
		sendMsg(flag,arg1,0,null);
	}
	private void sendMsg(int flag) {
		sendMsg(flag,0,0,null);
	}
	private void sendMsg(int flag,int arg1,int arg2,Object object) {
		Message msg = new Message();
		msg.arg1 = arg1;
		msg.arg2 = arg2;
		msg.what = flag;
		msg.obj = object;
		hander.sendMessage(msg);
	}

}
